<template>
  <div>
    <!-- 菜单区 -->
    <van-dropdown-menu>
      <van-dropdown-item
        title="状态"
        v-model="tabletittle"
        :options="option1"
        @change="search"
        lazy-render
        :value="5"
      />
      <van-dropdown-item title="筛选">
        <van-cell center title="搜索" style="padding: 10px 45px">
          <template #right-icon>
            <input
              type="text"
              v-model="querInfo.searchinput"
              style="border: solid 1px #ccc; width: 80%; height: 20px"
            />
          </template>
        </van-cell>
        <div style="padding: 5px 16px">
          <van-button type="danger" block round @click="searchclick"
            >搜索</van-button
          >
        </div>
      </van-dropdown-item>
      <van-dropdown-item title="操作">
        <van-row>
          <van-col span="12">
            <h1>{{ '派单 已选:' + orders.length }}</h1>
            <!-- 树形控件 -->
            <el-tree
              :props="treeProps"
              :load="loadProps"
              lazy
              show-checkbox
              accordion
              check-strictly
              node-key="_id"
              ref="treeRef"
            ></el-tree>
            <div style="padding: 5px 16px">
              <van-button
                type="primary"
                block
                round
                @click="sendorders($refs.treeRef.getCheckedNodes())"
                >派 单</van-button
              >
            </div>
          </van-col>
          <van-col span="12">
            <div>
              <van-button type="primary" @click="recallshow = true"
                >撤 单</van-button
              >
              <van-button
                type="primary"
                @click="takeback"
                v-if="user.power != 4"
                >收 单</van-button
              >
            </div>
            <van-button
              type="primary"
              block
              round
              to="/sellZSumit"
              style="margin: 50px 0 0 0"
              >自产单</van-button
            >
          </van-col>
        </van-row>
      </van-dropdown-item>
    </van-dropdown-menu>

    <!-- 表格区 -->
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <el-table
        :data="tableData"
        @row-click="rowclick"
        @selection-change="selectorders"
      >
        <el-table-column type="selection"></el-table-column>
        <el-table-column label="改约时间" v-if="tabletittle == '1'">
          <template v-slot="scope">
            <span style="margin-left: 10px">{{
              new Date(scope.row.otherdate).toLocaleString('chinese', {
                hour12: false,
              })
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="接收时间" v-if="tabletittle != '1'">
          <template v-slot="scope">
            <span style="margin-left: 10px">{{
              new Date(scope.row.lead3qdate).toLocaleDateString().substring(5)
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="xlsx.区域" label="区域"></el-table-column>
        <el-table-column
          prop="xlsx.客户地址"
          label="客户地址"
          width="200"
        ></el-table-column>
        <el-table-column label="备注">
          <template v-slot="scope">
            <span style="margin-left: 10px">{{
              JSON.stringify(scope.row.memo).replace(/"/g, '')
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="lead3"
          label="业务员"
          show-overflow-tooltip
        ></el-table-column>
      </el-table>
      <van-pagination
        v-model="querInfo.pagenum"
        :items-per-page="querInfo.pagesize"
        :total-items="total"
        force-ellipses
        @change="pagenumchange"
      />
      <div style="height: 2rem"></div>
    </van-pull-refresh>
    <!-- 表格点击弹出框 -->
    <van-popup
      v-model="xqshow"
      position="bottom"
      closeable
      close-icon="close"
      :style="{ height: '80%' }"
      round
    >
      <van-icon name="phone-o" size="1rem" color="#07c160" @click="callphone" />
      <van-icon
        name="edit"
        size="1rem"
        color="#07c160"
        @click="memoshow = true"
      />
      <van-icon name="eye-o" size="1rem" color="#07c160" @click="gomsg" />
      <!-- 详细表格 -->
      <table border="6" width="100%" cellspacing="0" class="chenkbox">
        <caption>
          {{
            tittle[tabletittle]
          }}
        </caption>
        <tr v-for="(item, index) in tabletemp" v-if="index !== '客户号码'">
          <th>{{ index }}</th>
          <td>{{ item }}</td>
        </tr>
        <tr>
          <th>客户号码</th>
          <td>
            {{ tabletemp.客户号码.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') }}
          </td>
        </tr>
        <tr v-for="(item, index) in tableone.memo">
          <th>备注</th>
          <td>{{ item }}</td>
        </tr>
      </table>
      <div class="footerbutton">
        <van-button round type="danger" @click="showgy = true">改约</van-button>
        <van-button round type="warning" @click="feedback">反馈</van-button>
      </div>
    </van-popup>

    <!-- 撤单对话框 -->
    <van-dialog
      v-model="recallshow"
      title="撤单理由"
      :before-close="recall"
      show-cancel-button
    >
      <van-field
        v-model="recalltext"
        type="textarea"
        clearable
        left-icon="music-o"
        placeholder="请输入撤单留言"
      />
    </van-dialog>

    <!-- 改约弹出 -->
    <van-popup v-model="showgy" position="bottom" label="离开时间">
      <van-datetime-picker
        type="datetime"
        :min-date="new Date()"
        @cancel="showgy = false"
        @confirm="onConfirmgy"
      />
    </van-popup>

    <!-- 备注对话框 -->
    <van-dialog
      v-model="memoshow"
      title="订单备注"
      :before-close="memo"
      show-cancel-button
    >
      <van-field
        v-model="memeotext"
        type="textarea"
        clearable
        left-icon="music-o"
        placeholder="请输入备注"
      />
    </van-dialog>

    <!-- 订单跟踪 -->
    <el-dialog title="查看进度" :visible.sync="goDialogVisible" width="400px">
      <el-timeline reverse>
        <el-timeline-item
          v-for="(activity, index) in goDate"
          size="large"
          :key="index"
          :icon="activity.icon"
          :type="activity.type"
          :timestamp="
            new Date(activity.time).toLocaleString('chinese', { hour12: false })
          "
          >{{ activity.context }}</el-timeline-item
        >
      </el-timeline>
    </el-dialog>
  </div>
</template>

<script>
import { Toast, Notify, Dialog } from 'vant'
export default {
  components: {
    'van-dialog': Dialog.Component,
  },
  data() {
    return {
      goDialogVisible: false,
      showgy: false,
      memoshow: false,
      memeotext: '',
      // 筛选
      tabletittle: 999,
      option1: [
        { text: '未派单', value: 888 },
        { text: '未反馈', value: 0 },
        { text: '改约', value: 1 },
        { text: '撤单', value: 2 },
        { text: '收回', value: 3 },
        { text: '待审核', value: 4 },
        { text: '通过', value: 5 },
        { text: '不通过', value: 6 },
        { text: '回捞', value: 7 },
        { text: '全部', value: 999 },
      ],
      tittle: {
        888: '未派单',
        0: '未反馈',
        1: '改约',
        2: '撤单',
        3: '收回',
        4: '待审核',
        5: '通过',
        6: '不通过',
        7: '回捞',
        999: '全部',
      },
      total: 0,
      // 搜索请求参数 get
      querInfo: {
        // 页数
        pagenum: 1,
        // 每页数量
        pagesize: 50,
        // 搜索框的值
        searchinput: '',
        // 订单状态
        status: 999,
      },

      // 下拉刷新
      isLoading: false,
      // 表格数据
      tableData: [],
      // 给详细弹框索引数据
      tabletemp: { 客户号码: '6666666666' },
      // 详细弹框的id
      tableId: '',
      // 弹出框信息
      xqshow: false,
      // 撤单弹框
      recallshow: false,
      // 撤单理由
      recalltext: '',
      //表单
      form: {},
      //用户
      user: {},
      //表格选择数据
      orders: [],
      //   树形控件的属型绑定对象
      treeProps: {
        label: 'username',
        children: 'children',
        isLeaf: 'leaf',
      },
      tableone: {},
      goDate: [],
    }
  },
  created() {
    if (window.sessionStorage.getItem('hmquery') === null) {
      this.getOrderslist()
    } else {
      this.querInfo = JSON.parse(window.sessionStorage.getItem('hmquery'))
      this.getOrderslist()
    }
    this.user = JSON.parse(window.localStorage.getItem('user'))
  },
  methods: {
    //搜索按钮按下
    searchclick() {
      this.getOrderslist()
    },
    // 筛选
    search(value) {
      this.querInfo.status = value
      this.getOrderslist()
    },
    // 下拉刷新
    onRefresh() {
      this.getOrderslist()
    },
    // 表格点击事件
    rowclick(row, column, event) {
      this.tabletemp = row.xlsx
      this.tableId = row._id
      this.tableone = row
      this.form = row.form
      this.xqshow = true
    },
    // 反馈
    feedback() {
      this.$router.push({
        name: 'sellSubmit',
        params: {
          projectId: this.tableId,
          form: this.form,
          phoneNum: this.tabletemp.客户号码,
          gift: this.tableone.gift,
          gift2: this.tableone.gift2,
        },
      })
    },
    // 获取订单列表
    async getOrderslist() {
      const { data: res } = await this.$http.get('hx/sellbuylist/orderslist', {
        params: this.querInfo,
      })
      if (res.meta.status !== 200) {
        this.tableData = res.data
        this.isLoading = false
        return Notify({ type: 'danger', message: res.meta.msg })
      }
      this.total = res.total
      this.tableData = res.data
      this.option1[0].text = '未派单  ' + res.status[888]
      this.option1[1].text = '未反馈  ' + res.status[0]
      this.option1[2].text = '改约  ' + res.status[1]
      this.option1[3].text = '撤单  ' + res.status[2]
      this.option1[4].text = '收回  ' + res.status[3]
      this.option1[5].text = '待审核  ' + res.status[4]
      this.option1[6].text = '通过  ' + res.status[5]
      this.option1[7].text = '不通过  ' + res.status[6]
      this.option1[8].text = '回捞  ' + res.status[7]

      Toast({
        message: res.total + '条 ' + this.tittle[this.tabletittle],
        icon: 'like-o',
      })
      // 本期储存搜索
      window.sessionStorage.setItem('hmquery', JSON.stringify(this.querInfo))
      this.isLoading = false
    },
    // 改约
    async gaiyue(date) {
      const { data: res } = await this.$http.get('hx/sellbuylist/gaiyue', {
        params: { _id: this.tableId, date: date },
      })

      if (res.meta.status !== 200) {
        return Notify({ type: 'danger', message: res.meta.msg })
      }

      Notify({ type: 'success', message: res.meta.msg })
    },
    onConfirmgy(date) {
      Dialog.confirm({
        theme: 'round-button',
        title: '确定改约时间为?',
        message: date.toLocaleString('chinese', { hour12: false }),
      })
        .then(() => {
          this.gaiyue(date)
          this.showgy = false
        })
        .catch(() => {
          this.showgy = false
        })
    },
    // 拨打电话
    async callphone() {
      if (this.tabletemp.客户号码 === undefined) {
        return
      }
      const { data: res } = await this.$http.get('hx/sellbuylist/callphone', {
        params: { phonenum: this.tabletemp.客户号码, _id: this.tableId },
      })

      if (res.meta.status !== 200) {
        return Notify({ type: 'danger', message: res.meta.msg })
      }
      window.open('tel:' + res.meta.msg, '_self')
    },
    // 撤单
    async backout() {
      let ordersid = []
      this.orders.forEach((item, index) => {
        ordersid.push(item._id)
      })
      const { data: res } = await this.$http.get('hx/sellbuylist/backout', {
        params: {
          _id: ordersid,
          recalltext: this.recalltext,
        },
      })

      if (res.meta.status !== 200) {
        return Notify({ type: 'danger', message: res.meta.msg })
      }

      Notify({ type: 'success', message: res.meta.msg })
      this.getOrderslist()
    },
    recall: function (action, done) {
      if (action === 'confirm') {
        if (this.recalltext.replace(/\s+/g, '').length === 0) {
          Notify({ type: 'warning', message: '请输入内容!' })
        } else {
          if (this.orders.length === 0) {
            console.log(123)
            return Notify({ type: 'warning', message: '请选择要撤的单!' })
          } else {
            this.backout()
          }
        }
        done() // 关闭提示框
      } else if (action === 'cancel') {
        done() // 关闭提示框
      }
    },
    // 监听页码值 改变的事件
    pagenumchange(newPage) {
      this.querInfo.pagenum = newPage
      this.getOrderslist()
    },
    // 选择事件
    selectorders(val) {
      this.orders = val
    },
    // 动态加载人物
    async loadProps(node, resolve) {
      const { data: res } = await this.$http.get('hx/usertree', {
        params: node.data,
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 限制最高子节点 这里用isLeaf 不需要这个
      // if (node.level > 4) return resolve([])
      resolve(res.data)
    },
    // 派单按钮点击
    async sendorders(people) {
      if (this.orders.length === 0) {
        Notify({ type: 'danger', message: '请选择订单' })
      }

      if (people.length === 0) {
        Notify({ type: 'danger', message: '请选择收单人!' })
      }
      let orders = []
      this.orders.forEach((ele, item) => {
        orders.push(ele._id)
      })

      const { data: res } = await this.$http.put(
        '/hx/sellbuylist/sendorders',
        {
          people: people,
          orders: orders,
        },
        {
          params: this.querInfo,
        }
      )

      if (res.meta.status !== 200) return Toast(res.meta.msg)
      this.tableData = []
      Toast(res.meta.msg)
      this.tableData = res.data
    },
    // 项目备注
    async editmemo() {
      const { data: res } = await this.$http.get('hx/sellbuylist/memo', {
        params: {
          _id: this.tableId,
          memotext: this.memeotext,
        },
      })
      if (res.meta.status !== 200)
        return Notify({ type: 'danger', message: res.meta.msg })

      Notify({ type: 'success', message: res.meta.msg })
    },
    memo: function (action, done) {
      if (action === 'confirm') {
        if (this.memeotext.replace(/\s+/g, '').length === 0) {
          return Notify({ type: 'warning', message: '请输入内容!' })
        } else {
          this.editmemo()
        }
        done() // 关闭提示框
      } else if (action === 'cancel') {
        done() // 关闭提示框
      }
    },
    // 收单
    takeback() {
      if (this.orders.length === 0) {
        return this.$message.error('请选择订单! ')
      }
      let ordersid = []
      this.orders.forEach((item, index) => {
        ordersid.push(item._id)
      })
      Dialog.confirm({
        title: '收 回',
        message: '已选: ' + ordersid.length + ' 条! 确定收回吗?',
      })
        .then(async () => {
          const { data: res } = await this.$http.get(
            'hx/sellbuylist/takeback',
            {
              params: { _id: ordersid },
            }
          )
          if (res.meta.status !== 200) {
            return Notify({ type: 'warning', message: res.meta.msg })
          }
          Notify({ type: 'success', message: res.meta.msg })
          this.getOrderslist()
        })
        .catch(() => {
          Toast({
            message: '已取消',
            icon: 'like-o',
          })
        })
    },
    // 跟踪
    gomsg() {
      this.goDate = this.tableone.msg
      this.goDialogVisible = true
      this.xqshow = false
    },
  },
}
</script>

<style lang="less" scope>
.chenkbox {
  // margin: 0 50px;
  text-align: center;

  caption {
    color: mediumpurple;
    font-weight: bold;
    font-size: 30px;
  }
}

.footerbutton {
  position: fixed;
  bottom: 10px;
  margin: 0 20px;
  .van-button {
    width: 160px;
  }
}

.van-icon {
  margin: 0 10px;
}

.van-pagination {
  position: fixed;
  bottom: 1.3rem;
  width: 100%;
}
</style>